package com.jlg.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 *
 * author: huazhang
 * since : 2011-3-15
 */
public class DateUtil
{

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    public final static java.sql.Date string2Date(String dateString)
            throws java.lang.Exception
    {
        DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
        dateFormat.setLenient(false);
        java.util.Date timeDate = dateFormat.parse(dateString);
        java.sql.Date dateTime = new java.sql.Date(timeDate.getTime());
        return dateTime;
    }
    
    public static String dateFormat(String content)
    {
        try
        {
            String thisYear = sdf.format(new Date()).substring(0, 4);
            if (content.startsWith("-"))
            {
                content = content.substring(1);
            }
            String[] t = content.split("-|年|月|日|\\.|/");
            if (t == null)
            {
                return null;
            }
            String y = null;
            String m = null;
            String d = null;
            if (t.length == 2)
            {
                if (content.startsWith(thisYear))
                {
                    // eg. 2010-6
                    y = t[0];
                    m = t[1];
                    d = "01";
                }
                else
                {
                    y = thisYear;
                    m = t[0];
                    d = t[1];
                }
            }
            else if (t.length == 3)
            {
                y = t[0];
                m = t[1];
                d = t[2];
            }
            if (y == null || m == null || d == null)
            {
                return null;
            }
            int month = Integer.parseInt(m);
            int day = Integer.parseInt(d);
            if (month < 0 || month > 12 || day > 31 || day < 0)
            {
                return null;
            }
            return (y.length() < 4 ? "20" + y : y) + "-" + (m.length() < 2 ? "0" + m : m) + "-"
                    + (d.length() < 2 ? "0" + d : d);
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
